package com.xidian.zhiancloud.service.riskcontrol.riskidenva;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xidian.zhiancloud.dao.InformationMapper;
import com.xidian.zhiancloud.dao.riskcontrol.TRiskLedgerStatusMapper;
import com.xidian.zhiancloud.dao.riskcontrol.riskidenva.*;
import com.xidian.zhiancloud.dao.riskcontrol.riskpointslist.TEquipFacStatusMapper;
import com.xidian.zhiancloud.dao.syset.usermanage.OrganizationMapper;
import com.xidian.zhiancloud.model.Information;
import com.xidian.zhiancloud.model.riskcontrol.*;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.qo.BaseReqQuery;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 风险辨识评价计划
 */
@Service
public class TRiskIdentEvalStatusService extends ServiceImpl
        <TRiskIdentEvalStatusMapper,TRiskIdentEvalStatusList> {

    @Autowired
    TRiskIdentEvalStatusMapper tRiskIdentEvalStatusMapper;

    @Autowired
    TRiskTaskAllocationMapper tRiskTaskAllocationMapper;

    @Autowired
    TEquipFacStatusMapper tEquipFacStatusMapper;

    @Autowired
    HttpServletRequest request;

    @Autowired
    TRiskCheckProcessMapper tRiskCheckProcessMapper;

    @Autowired
    OrganizationMapper organizationMapper;

    @Autowired
    InformationMapper informationMapper;

    @Autowired
    TRiskProcessOperationRecordMapper tRiskProcessOperationRecordMapper;

    @Autowired
    TRiskLedgerStatusMapper tRiskLedgerStatusMapper;

    @Autowired
    TRiskCheckItemsMapper tRiskCheckItemsMapper;

    @Autowired
    TRiskJobCheckItemMapper tRiskJobCheckItemMapper;

    @Autowired
    TRiskProcessInspectionItemMapper tRiskProcessInspectionItemMapper;

    @Autowired
    TRiskAssessmentMeasuresMapper tRiskAssessmentMeasuresMapper;

    @Autowired
    TRiskValueLevelMapper tRiskValueLevelMapper;

    //超级管理员登录
    public Page<TRiskIdentEvalStatusList> getTRiIdeEvalStaSuperAdmin
            (BaseReqQuery reqdata, Long companyId,String state,
             String riskpointType, String userId,String discerner,String evaluator,
             String auditor,String type) {
        PageHelper.startPage(reqdata.getPageNum(), reqdata.getPageSize());
        Page<TRiskIdentEvalStatusList> pagedata =tRiskIdentEvalStatusMapper
           .getTRiIdeEvalStaSuperAdmin(reqdata.getSearchKey(),
            companyId,state,riskpointType,userId,discerner,evaluator,auditor,type);
        return pagedata;
    }

    public Page<TRiskIdentEvalStatusList> getTRiIdeEvalSta(BaseReqQuery reqdata, Long companyId,
            String state,String riskpointType, String userId,String discerner,String evaluator,String type){
        PageHelper.startPage(reqdata.getPageNum(), reqdata.getPageSize());
        Page<TRiskIdentEvalStatusList> pagedata =tRiskIdentEvalStatusMapper
            .getTRiIdeEvalSta(reqdata.getSearchKey(),
                companyId,state,riskpointType,userId,discerner,evaluator,type);
        return pagedata;
    }

    //风险评价审核里面的列表
    public Page<TRiskIdentEvalStatusList> getTRiIdeEvalStaAudit(BaseReqQuery reqdata, 
           Long companyId,String state,String riskpointType, String auditor,String type,String userId) {
        PageHelper.startPage(reqdata.getPageNum(), reqdata.getPageSize());
        Page<TRiskIdentEvalStatusList> pagedata =tRiskIdentEvalStatusMapper.getTRiIdeEvalStaAudit
            (reqdata.getSearchKey(),companyId,state,riskpointType,auditor,type,userId);
        return pagedata;
    }
    
    public List<TRiskIdentEvalStatusList> getTRiskIdentEvalStatusCreateId(Long companyId,String userId){
        return tRiskIdentEvalStatusMapper.getTRiskIdentEvalStatusCreateId(companyId,userId);
    }

    public List<String> getTRiskIdentEvalStatusAndRecipientIdList(Long companyId){
        return tRiskIdentEvalStatusMapper.getTRiskIdentEvalStatusAndRecipientIdList(companyId);
    }

    public TRiskIdentEvalStatusList getByIds(Long companyId,String id){
        return tRiskIdentEvalStatusMapper.getByIds(companyId,id);
    }
    
    public List<TRiskIdentEvalStatusList> getById(Long companyId,String id){
        return tRiskIdentEvalStatusMapper.getById(companyId,id);
    }

    public int removeTRiskIdentEvalStatus(String id){
        List<String> list = getList(id);
        return tRiskIdentEvalStatusMapper.removeTRiskIdentEvalStatus(list);
    }

    /**
     * id放入list
     * @param id id(多个已逗号分隔)
     * @return List集合
     */
    public List<String> getList(String id) {
        List<String> list = new ArrayList<String>();
        String[] str = id.split(",");
        for (int i = 0; i < str.length; i++) {
            list.add(str[i]);
        }
        return list;
    }

    //添加
    @Transactional
    public int insertTRiskIdentEvalStatusList(TRiskIdentEvalStatusList data,
               Long companyId,String tefsId) {

        int resu = tRiskIdentEvalStatusMapper.insertTRiskIdentEvalStatusList
            (data, companyId);
        Long triesId = data.getId();//新增的风险辨识评价计划的ID
        
        List<TRiskTaskAllocationList> tRiskTaskAllocationList = new
            ArrayList<>();
        List<TRiskCheckProcessList> checkProceList = new ArrayList<>();

        List<TRiskProcessOperationRecordList> riProOperRecList = new ArrayList<>();
        
        String[] tefsIds = tefsId.split(",");//风险点ID
        String[] identificationMethodId = request.getParameter
            ("identificationMethodId").split(",");
        String[] evaluationMethodId = request.getParameter
            ("evaluationMethodId").split(",");
        String[] personidenEva = request.getParameter("personidenEva").split(",");
        
        List<Long> triesIdList = new ArrayList<>();
        
        //风险辨识评价计划的ID
        for(int j = 0; j < tefsIds.length; j++){
            triesIdList.add(triesId);
        }
        //安全部门
        Organization isafeorg = organizationMapper.getByIsafeorg(companyId);
        //顶级部门
        Organization topPid = organizationMapper.getByTopPid(companyId);
        //父级部门
        List<String> orgList = Arrays.asList(data.getOrgId().split(","));
        List<Organization> pidList = organizationMapper.getByLeadUserid
            (companyId, orgList);

        List<String> processNameList = new ArrayList<>();
            processNameList.add("1");//计划创建人
            processNameList.add("2");//计划分解人
            processNameList.add("3");//辨识人
            processNameList.add("4");//评价人
            processNameList.add("5");//审核人1
            processNameList.add("6");//审核人2
            processNameList.add("7");//审核人3

        List<String> processStateList = new ArrayList<>();
            processStateList.add("1");
            processStateList.add("1");
            processStateList.add("1");
            processStateList.add("1");
            processStateList.add("1");
            processStateList.add("1");
            processStateList.add("1");
        
        if (resu!=0){
            for (int j = 0; j < pidList.size(); j++) {

            TRiskTaskAllocationList tRiskTaskAllocation = new TRiskTaskAllocationList();
            tRiskTaskAllocation.setCompanyId(companyId);
            tRiskTaskAllocation.setTriskidentevalsId(triesIdList.get(j).intValue());
            tRiskTaskAllocation.setRiskpointsId
                (Integer.parseInt(tefsIds[j]));
            tRiskTaskAllocation.setIdentificationMethodId
                (identificationMethodId[j]);
            tRiskTaskAllocation.setEvaluationMethodId(evaluationMethodId[j]);
            tRiskTaskAllocation.setOrgid(pidList.get(j).getId().toString());
            tRiskTaskAllocation.setPersonidenEva(personidenEva[j]);
            tRiskTaskAllocation.setDiscerner(personidenEva[j]);
            tRiskTaskAllocation.setEvaluator(personidenEva[j]);
            tRiskTaskAllocation.setAuditor(pidList.get(j).getLeadUserid().toString());
            tRiskTaskAllocation.setCreateId(data.getCreateId());
            tRiskTaskAllocationList.add(tRiskTaskAllocation);

            Information info = new Information();
            info.setTitle("风险辨识评价计划");
            info.setDepartment(String.valueOf(companyId));
            info.setStatus("0");
            info.setDetails("风险辨识评价计划已添加,请尽快发布!!");
            info.setSendId(Long.valueOf(data.getCreateId()));//发送者
            info.setTargetId(pidList.get(j).getLeadUserid().longValue());//接收者
            info.setCreateTime(new Date());
            info.setUpdateTime(new Date());
            informationMapper.insertInfo(info);
            }
            tRiskTaskAllocationMapper.insertTRiskTaskAllocationList(tRiskTaskAllocationList);
        } 
        if (resu!=0){
                
                for (int j = 0; j < pidList.size(); j++) {
                    
                    Organization pidLeadUserId= organizationMapper
                        .getByPidAndLeadUserId(companyId,pidList.get(j).getPid());

                    TRiskCheckProcessList tRiskCheckProcess = new TRiskCheckProcessList();
                    tRiskCheckProcess.setCompanyId(companyId);
                    tRiskCheckProcess.setTriskidentevalsId(triesId.intValue());
                    tRiskCheckProcess.setTaskAllocatId
                        (tRiskTaskAllocationList.get(j).getId().intValue());
                    tRiskCheckProcess.setCreateId(data.getCreateId());
                    tRiskCheckProcess.setPersonideneva(personidenEva[j]);
                    tRiskCheckProcess.setDiscerner(personidenEva[j]);
                    tRiskCheckProcess.setEvaluator(personidenEva[j]);
                    
                    tRiskCheckProcess.setDepaReviewer
                        (String.valueOf(pidLeadUserId.getLeadUserid()));
                    
                    tRiskCheckProcess.setSecurityReviewer
                        (String.valueOf(isafeorg.getLeadUserid()));
                    tRiskCheckProcess.setEndReviewer
                        (String.valueOf(topPid.getLeadUserid()));
                    checkProceList.add(tRiskCheckProcess);
            }
            tRiskCheckProcessMapper.insertTRiskCheckProcess(checkProceList);
        }

        if (resu!=0) {
            
            for (int j = 0; j < pidList.size(); j++) {

                List<String> oldIdList = new ArrayList<>();
                oldIdList.add(data.getCreateId());
                oldIdList.add(personidenEva[j]);
                oldIdList.add(personidenEva[j]);
                oldIdList.add(personidenEva[j]);
                oldIdList.add(String.valueOf(pidList.get(j).getLeadUserid()));
                oldIdList.add(String.valueOf(isafeorg.getLeadUserid()));
                oldIdList.add(String.valueOf(topPid.getLeadUserid()));
                
                for (int i = 0; i < processNameList.size(); i++) {
                    
                    TRiskProcessOperationRecordList riProOperRec =
                        new TRiskProcessOperationRecordList();
                    riProOperRec.setCompanyId(companyId);
                    riProOperRec.setTriskidentevalsId(triesId.intValue());
                    riProOperRec.setTaskAllocatId(tRiskTaskAllocationList.get(j).getId().intValue());
                    riProOperRec.setProcessOperationType(processNameList.get(i));
                    riProOperRec.setOperator(Integer.valueOf(oldIdList.get(i)));
                    riProOperRec.setOperatingTime(new Date());
                    riProOperRec.setState(processStateList.get(i));
                    riProOperRecList.add(riProOperRec);
                    
                }
                
            }
            
            tRiskProcessOperationRecordMapper.insertRiProOperRec(riProOperRecList);
            
        }    
        return resu;
    }

    //编辑
    public int updateIdentEval(Long companyId,String riskName,Date startTime,Date deadlineIden,
           Date deadlineEval,String remarks,String riskpointType,String id,
           String taskAllocatId,String tefsId,Long userId) {
       int res=tRiskIdentEvalStatusMapper.updateTRiskIdentEvalStatus
           (riskName,startTime,deadlineIden,deadlineEval,remarks,riskpointType,id);

       if (res!=0) {
           int allRes=tRiskTaskAllocationMapper.removeByTriskidentevalsId(companyId,id);
           tRiskProcessOperationRecordMapper.deleteByTaskAllId(companyId,id,taskAllocatId);

           List<TRiskTaskAllocationList> tRiskTaskAllocationList = new
               ArrayList<>();
           List<TRiskCheckProcessList> checkProceList = new ArrayList<>();

           List<TRiskProcessOperationRecordList> riProOperRecList = new ArrayList<>();

           String[] tefsIds = tefsId.split(",");//风险点ID
           String[] identificationMethodId = request.getParameter
               ("identificationMethodId").split(",");
           String[] evaluationMethodId = request.getParameter
               ("evaluationMethodId").split(",");

           List<Long> triesIdList = new ArrayList<>();

           for(int j = 0; j < tefsIds.length; j++){
               triesIdList.add(Long.valueOf(id));
           }
           //安全部门
           Organization isafeorg = organizationMapper.getByIsafeorg(companyId);
           //顶级部门
           Organization topPid = organizationMapper.getByTopPid(companyId);
           //父级部门
           List<String> orgList = Arrays.asList(request.getParameter
               ("orgId").split(","));
           List<Organization> pidList = organizationMapper.getByLeadUserid
               (companyId, orgList);
           
           List<String> processNameList = new ArrayList<>();
           processNameList.add("1");//计划创建人
           processNameList.add("2");//计划分解人
           processNameList.add("3");//辨识人
           processNameList.add("4");//评价人
           processNameList.add("5");//审核人1
           processNameList.add("6");//审核人2
           processNameList.add("7");//审核人3

           List<String> processStateList = new ArrayList<>();
           processStateList.add("1");
           processStateList.add("1");
           processStateList.add("1");
           processStateList.add("1");
           processStateList.add("1");
           processStateList.add("1");
           processStateList.add("1");
           
           if(allRes!=0){

               for (int j = 0; j < pidList.size(); j++) {

                   TRiskTaskAllocationList tRiskTaskAllocation = new TRiskTaskAllocationList();
                   tRiskTaskAllocation.setCompanyId(companyId);
                   tRiskTaskAllocation.setTriskidentevalsId(triesIdList.get(j).intValue());
                   tRiskTaskAllocation.setRiskpointsId
                       (Integer.parseInt(tefsIds[j]));
                   tRiskTaskAllocation.setIdentificationMethodId
                       (identificationMethodId[j]);
                   tRiskTaskAllocation.setEvaluationMethodId(evaluationMethodId[j]);
                   tRiskTaskAllocation.setOrgid(pidList.get(j).getId().toString());
                   tRiskTaskAllocation.setPersonidenEva(pidList.get(j).getLeadUserid().toString());
                   tRiskTaskAllocation.setDiscerner(pidList.get(j).getLeadUserid().toString());
                   tRiskTaskAllocation.setEvaluator(pidList.get(j).getLeadUserid().toString());
                   tRiskTaskAllocation.setAuditor(pidList.get(j).getLeadUserid().toString());
                   tRiskTaskAllocation.setCreateId(userId.toString());
                   tRiskTaskAllocationList.add(tRiskTaskAllocation);

                   Information info = new Information();
                   info.setTitle("风险辨识评价计划");
                   info.setDepartment(String.valueOf(companyId));
                   info.setStatus("0");
                   info.setDetails("风险辨识评价计划已添加,请尽快发布!!");
                   info.setSendId(userId);//发送者
                   info.setTargetId(pidList.get(j).getLeadUserid().longValue());//接收者
                   info.setCreateTime(new Date());
                   info.setUpdateTime(new Date());
                   informationMapper.insertInfo(info);
               }
               
               tRiskTaskAllocationMapper.insertTRiskTaskAllocationList(tRiskTaskAllocationList);

                   for (int j = 0; j < pidList.size(); j++) {

                       Organization pidLeadUserId= organizationMapper
                           .getByPidAndLeadUserId(companyId,pidList.get(j).getPid());

                       TRiskCheckProcessList tRiskCheckProcess = new TRiskCheckProcessList();
                       tRiskCheckProcess.setCompanyId(companyId);
                       tRiskCheckProcess.setTriskidentevalsId(Integer.valueOf(id));
                       tRiskCheckProcess.setTaskAllocatId
                           (tRiskTaskAllocationList.get(j).getId().intValue());
                       tRiskCheckProcess.setCreateId(userId.toString());
                       tRiskCheckProcess.setPersonideneva(pidList.get(j).getLeadUserid().toString());
                       tRiskCheckProcess.setDiscerner(pidList.get(j).getLeadUserid().toString());
                       tRiskCheckProcess.setEvaluator(pidList.get(j).getLeadUserid().toString());

                       tRiskCheckProcess.setDepaReviewer
                           (String.valueOf(pidLeadUserId.getLeadUserid()));

                       tRiskCheckProcess.setSecurityReviewer
                           (String.valueOf(isafeorg.getLeadUserid()));
                       tRiskCheckProcess.setEndReviewer
                           (String.valueOf(topPid.getLeadUserid()));
                       checkProceList.add(tRiskCheckProcess);
                   }
                   tRiskCheckProcessMapper.insertTRiskCheckProcess(checkProceList);
               }

                   for (int j = 0; j < pidList.size(); j++) {

                       List<String> oldIdList = new ArrayList<>();
                       oldIdList.add(userId.toString());
                       oldIdList.add(String.valueOf(pidList.get(j).getLeadUserid()));
                       oldIdList.add(String.valueOf(pidList.get(j).getLeadUserid()));
                       oldIdList.add(String.valueOf(pidList.get(j).getLeadUserid()));
                       oldIdList.add(String.valueOf(pidList.get(j).getLeadUserid()));
                       oldIdList.add(String.valueOf(isafeorg.getLeadUserid()));
                       oldIdList.add(String.valueOf(topPid.getLeadUserid()));

                       for (int i = 0; i < processNameList.size(); i++) {

                           TRiskProcessOperationRecordList riProOperRec =
                               new TRiskProcessOperationRecordList();
                           riProOperRec.setCompanyId(companyId);
                           riProOperRec.setTriskidentevalsId(Integer.valueOf(id));
                           riProOperRec.setTaskAllocatId(tRiskTaskAllocationList.get(j).getId().intValue());
                           riProOperRec.setProcessOperationType(processNameList.get(i));
                           riProOperRec.setOperator(Integer.valueOf(oldIdList.get(i)));
                           riProOperRec.setOperatingTime(new Date());
                           riProOperRec.setState(processStateList.get(i));
                           riProOperRecList.add(riProOperRec);

                       }

                   }

                   tRiskProcessOperationRecordMapper.insertRiProOperRec(riProOperRecList);

           }

       return res;
    }

    //编辑
    public int updateIdentEvalSta(String riskName,Date startTime,Date deadlineIden,
           Date deadlineEval,String remarks,String riskpointType,Long companyId,String tefsId, 
          String id, String evaluationMethodIds) {
        tRiskIdentEvalStatusMapper.updateTRiskIdentEvalStatus(riskName,startTime,deadlineIden,
            deadlineEval,remarks,riskpointType,id);
        List<TRiskTaskAllocationList> tRiskTaskAllocationList = new
                ArrayList<>();
        String[] tefsIds= tefsId.split(",");//风险点ID
        String[] identificationMethodId= request.getParameter
                ("identificationMethodId").split(",");
        String[] evaluationMethodId =evaluationMethodIds.split(",");
        String[] orgid =request.getParameter("orgid").split(",");
        String[] personidenEva =request.getParameter
                ("personidenEva").split(",");

        //安全部门
        Organization isafeorg = organizationMapper.getByIsafeorg(companyId);
        //顶级部门
        Organization topPid = organizationMapper.getByTopPid(companyId);
        //父级部门
        List<String> orgList = new ArrayList<>();
        for (int i = 0; i < orgid.length; i++) {
            orgList.add(orgid[i]);
        }
        List<Organization> pidList = organizationMapper.getByLeadUserid
            (companyId, orgList);

        List<String> processNameList = new ArrayList<>();
            processNameList.add("1");//计划创建人
            processNameList.add("2");//计划分解人
            processNameList.add("3");//辨识人
            processNameList.add("4");//评价人
            processNameList.add("5");//审核人1
            processNameList.add("6");//审核人2
            processNameList.add("7");//审核人3

        List<String> processStateList = new ArrayList<>();
        processStateList.add("1");
        processStateList.add("2");
        processStateList.add("3");
        processStateList.add("4");
        processStateList.add("5");
        processStateList.add("5");
        processStateList.add("5");
        
        for (int i = 0; i < evaluationMethodId.length; i++) {
            TRiskTaskAllocationList tRiskTaskAllocation = new
                    TRiskTaskAllocationList();
            tRiskTaskAllocation.setCompanyId(companyId);
            tRiskTaskAllocation.setTriskidentevalsId(Integer.valueOf(id));
            tRiskTaskAllocation.setRiskpointsId
                    (Integer.parseInt(tefsIds[i]));
            tRiskTaskAllocation.setIdentificationMethodId
                    (identificationMethodId[i]);
            tRiskTaskAllocation.setEvaluationMethodId(evaluationMethodId[i]);
            tRiskTaskAllocation.setOrgid(orgid[i]);
            tRiskTaskAllocation.setPersonidenEva(personidenEva[i]);
            tRiskTaskAllocation.setDiscerner(personidenEva[i]);
            tRiskTaskAllocation.setEvaluator(personidenEva[i]);
            tRiskTaskAllocation.setAuditor(personidenEva[i]);
            tRiskTaskAllocation.setRecognitiontime(null);
            tRiskTaskAllocation.setEvaluationtime(null);
            tRiskTaskAllocation.setProposal(null);
            //tRiskTaskAllocation.setCreateId(data.getCreateId());
            tRiskTaskAllocationList.add(tRiskTaskAllocation);

        }
        return tRiskTaskAllocationMapper.insertDiscernerAndEvaluator
                (tRiskTaskAllocationList);
    }

    //发布(之后的状态为分解中) @param id 风险辨识评价计划ID
    public void releaseRiskIdenEva(Long companyId,String id,String state,Long userId){
        List<TRiskTaskAllocationList> allList=tRiskTaskAllocationMapper.
            selectByNewTaskAll(companyId,id);
        StringBuilder str  = new StringBuilder();
        List<String> recipientIdList = new ArrayList<>();
        for (int i = 0; i < allList.size(); i++) {
            recipientIdList.add(allList.get(i).getPersonidenEva());
        }
        for(int i=0;i<recipientIdList.size();i++){
            if(i==recipientIdList.size()-1)//当循环到最后一个的时候 就不添加逗号,
            {
                str.append(recipientIdList.get(i));
            }
            else {
                str.append(recipientIdList.get(i));
                str.append(",");
            }
        }
        String recipientIds = str.toString();
        int result = tRiskIdentEvalStatusMapper.releaseRiskIdenEva
            (companyId,id,state,recipientIds);
        if(result == 1){
            String status = "2";//风险点分解中的状态
           tRiskTaskAllocationMapper.releaseRTaskAllocation(companyId,id,state,status);
            //发布成功/分解中
           tRiskProcessOperationRecordMapper.updateByIdAndPublishedOk(companyId, id);
        }
    }

    //派发按钮(派发之后的状态为辨识中) @param id 风险辨识评价计划ID
    public void decomposeRiskIdenEva(Long companyId,String id,String state,Long userId){
        List<TRiskTaskAllocationList> allList=tRiskTaskAllocationMapper.
            selectByNewTaskAll(companyId,id);
        StringBuilder str  = new StringBuilder();
        List<String> recipientIdList = new ArrayList<>(); 
        for (int i = 0; i < allList.size(); i++) {
            recipientIdList.add(allList.get(i).getDiscerner());
        }
        for(int i=0;i<recipientIdList.size();i++){
            if(i==recipientIdList.size()-1)//当循环到最后一个的时候 就不添加逗号,
            {
                str.append(recipientIdList.get(i));
            }
            else {
                str.append(recipientIdList.get(i));
                str.append(",");
            }
        }
        String recipientIds = str.toString();
        int result = tRiskIdentEvalStatusMapper.decomposeRiskIdenEva
            (companyId,id,state,recipientIds);
        if(result == 1) {
            String status = "3";//风险点辨识中的状态
            tRiskTaskAllocationMapper.decomposeRTaskAllocation
                (companyId,id,state,status);
        }
        List<TRiskTaskAllocationList> taskAllList = tRiskTaskAllocationMapper
                .getById(companyId, id);
        for (TRiskTaskAllocationList  taskAll : taskAllList) {

            Information info = new Information();
            info.setTitle("风险辨识评价计划等待辨识");
            info.setDepartment(String.valueOf(companyId));
            info.setStatus("0");
            info.setDetails("风险辨识评价计划已分解,请尽快辨识!!");
            info.setSendId(Long.valueOf(taskAll.getPersonidenEva()));//发送者
            info.setTargetId(Long.valueOf(taskAll.getDiscerner()));//接收者
            info.setCreateTime(new Date());
            info.setUpdateTime(new Date());
            informationMapper.insertInfo(info);

        }
        //分解完成/辨识中
        tRiskProcessOperationRecordMapper.updateByIdAndResolveOk(companyId, id);
    }

    //风险辨识提交按钮后的状态为--状态 评价中(4)
    public void identificationRiskIdenEva(Long companyId,String id,String state,Long userId){
        List<String> list = getList(id);
        List<TRiskTaskAllocationList> allList=tRiskTaskAllocationMapper.
            selectByNewTaskAll(companyId,id);
        StringBuilder str  = new StringBuilder();
        List<String> recipientIdList = new ArrayList<>();
        for (int i = 0; i < allList.size(); i++) {
            recipientIdList.add(allList.get(i).getEvaluator());
        }
        for(int i=0;i<recipientIdList.size();i++) {
            if(i==recipientIdList.size()-1)//当循环到最后一个的时候 就不添加逗号,
            {
                str.append(recipientIdList.get(i));
            }
            else {
                str.append(recipientIdList.get(i));
                str.append(",");
            }
        }
        String recipientIds = str.toString();
        int result = tRiskIdentEvalStatusMapper.identificationRiskIdenEva
                (companyId,list,state,recipientIds);
        if(result == 1) {
            String status = "4";//风险点评价中的状态
            tRiskTaskAllocationMapper.identificationTaskAllocat
                    (companyId, list, state,status);
        }

        List<TRiskTaskAllocationList> taskAllList = tRiskTaskAllocationMapper
                .getById(companyId, id);
        for (TRiskTaskAllocationList  taskAll : taskAllList) {

            Information info = new Information();
            info.setTitle("风险辨识评价计划等待评价");
            info.setDepartment(String.valueOf(companyId));
            info.setStatus("0");
            info.setDetails("风险辨识评价计划已辨识,请尽快评价 !!");
            info.setSendId(Long.valueOf(taskAll.getDiscerner()));//发送者
            info.setTargetId(Long.valueOf(taskAll.getEvaluator()));//接收者
            info.setCreateTime(new Date());
            info.setUpdateTime(new Date());
            informationMapper.insertInfo(info);

        }   
            //辨识完成/评价中
            tRiskProcessOperationRecordMapper.updateByIdAndRecognizeOk(companyId, id);
    }

    //评价中的退回按钮
    public void evaluationDecomposeRiskIdenEva(
            Long companyId,String id,String state,Long userId){
        List<TRiskTaskAllocationList> allList=tRiskTaskAllocationMapper.
            selectByNewTaskAll(companyId,id);
        StringBuilder str  = new StringBuilder();
        List<String> recipientIdList = new ArrayList<>();
        for (int i = 0; i < allList.size(); i++) {
            recipientIdList.add(allList.get(i).getDiscerner());
        }
        for(int i=0;i<recipientIdList.size();i++){
            if(i==recipientIdList.size()-1)//当循环到最后一个的时候 就不添加逗号,
            {
                str.append(recipientIdList.get(i));
            }
            else {
                str.append(recipientIdList.get(i));
                str.append(",");
            }
        }
        String recipientIds = str.toString();
        int result = tRiskIdentEvalStatusMapper.evaluationDecomposeRiskIdenEva
                (companyId,id,state,recipientIds);
        List<String> list = getList(id);
        if(result == 1){
            String status = "6";//风险点评价中 退回后状态辨识中
            tRiskTaskAllocationMapper.evaluationDecomposeRTaskAllocation(companyId,
                    list,state,status);
        }
        List<TRiskTaskAllocationList> taskAllList = tRiskTaskAllocationMapper
                .getById(companyId, id);
        for (TRiskTaskAllocationList  taskAll : taskAllList) {

            Information info = new Information();
            info.setTitle("风险辨识评价计划等待辨识");
            info.setDepartment(String.valueOf(companyId));
            info.setStatus("0");
            info.setDetails("风险辨识评价计划已分解,请尽快辨识!!");
            info.setSendId(Long.valueOf(taskAll.getPersonidenEva()));//发送者
            info.setTargetId(Long.valueOf(taskAll.getDiscerner()));//接收者
            info.setCreateTime(new Date());
            info.setUpdateTime(new Date());
            informationMapper.insertInfo(info);

        }

    }

    //风险辨识评价计划-评价提交(评价计划确定成功之后将状态待审核/审核中)
    public void evaluateRiskIdenEva(Long companyId,String id,String state,Long userId){
        List<String> list = getList(id);
        List<TRiskCheckProcessList> allList=tRiskCheckProcessMapper.
            getByCheckProcessAndTRiskidentevalsId(companyId,id);
        StringBuilder str  = new StringBuilder();
        List<String> recipientIdList = new ArrayList<>();
        for (int i = 0; i < allList.size(); i++) {
            recipientIdList.add(allList.get(i).getDepaReviewer());
        }
        for(int i=0;i<recipientIdList.size();i++){
            if(i==recipientIdList.size()-1)//当循环到最后一个的时候 就不添加逗号,
            {
                str.append(recipientIdList.get(i));
            }
            else {
                str.append(recipientIdList.get(i));
                str.append(",");
            }
        }
        String recipientIds = str.toString();
        int result = tRiskIdentEvalStatusMapper.evaluateRiskIdenEva
                (companyId,list,state,recipientIds);
        if(result == 1) {
            String status = "5";//风险点审核中的状态
            tRiskTaskAllocationMapper.evaluateRTaskAllocation
                    (companyId, list, state,status);
        }

        List<TRiskTaskAllocationList> taskAllList = tRiskTaskAllocationMapper
                .getById(companyId,id);
        for (TRiskTaskAllocationList  taskAll : taskAllList) {

            Information info = new Information();
            info.setTitle("风险辨识评价计划等待审核");
            info.setDepartment(String.valueOf(companyId));
            info.setStatus("0");
            info.setDetails("风险辨识评价计划已评价,请尽快审核!!");
            info.setSendId(Long.valueOf(taskAll.getEvaluator()));//发送者
            info.setTargetId(Long.valueOf(taskAll.getEvaluator()));//接收者
            info.setCreateTime(new Date());
            info.setUpdateTime(new Date());
            informationMapper.insertInfo(info);

        }
        //辨识完成/评价中
        tRiskProcessOperationRecordMapper.updateByIdAndAppraiseOk(companyId, id);
    }

    public void evaluationRiskIdenEvaAudit(Long companyId,String id){
        tRiskIdentEvalStatusMapper.evaluationRiskIdenEvaAudit(companyId,id);
    }

    //部门审核不通过
    public void depaNoPassReview (Long companyId,String id,String states,String auditfind,Long userId) {
        List<TRiskTaskAllocationList> allList=tRiskTaskAllocationMapper.
            selectByNewTaskAll(companyId,id);
        String taAllId = allList.get(0).getId().toString();
        StringBuilder str  = new StringBuilder();
        List<String> recipientIdList = new ArrayList<>();
            for (int i = 0; i < allList.size(); i++) {
                recipientIdList.add(allList.get(i).getDiscerner());
            }
            for(int i=0;i<recipientIdList.size();i++){
                if(i==recipientIdList.size()-1)//当循环到最后一个的时候 就不添加逗号,
                {
                    str.append(recipientIdList.get(i));
                }
                else {
                    str.append(recipientIdList.get(i));
                    str.append(",");
                }
            }
        String recipientIds = str.toString();
        int result = tRiskIdentEvalStatusMapper.depaNoPassReview(companyId, id, states,recipientIds);
        if (result == 1) {
            String status = "9";//不通过
            int tAllResult = tRiskTaskAllocationMapper.depaNoPassReview(companyId, id, states,status);
            if (tAllResult > 0) {
                //1号审核不通过
                tRiskProcessOperationRecordMapper.updateByIdAndCompletedOneNoPass(companyId,id,taAllId);
            }
        }
    }

    //部门审核通过
    public void depaPassReview(Long companyId,String id,String states,String auditfind,Long userId) {
        //安全部门
        Organization isafeorg = organizationMapper.getByIsafeorg(companyId);
        List<TRiskTaskAllocationList> allList=tRiskTaskAllocationMapper.
            selectByNewTaskAll(companyId,id);
        String taAllId = allList.get(0).getId().toString();
        String recipientIds = String.valueOf(isafeorg.getLeadUserid());
        int result = tRiskIdentEvalStatusMapper.depaPassReview(companyId, id, states,recipientIds);
        if(result == 1) {
            String status = "10";//通过
           int tAllResult = tRiskTaskAllocationMapper.depaPassReview(companyId, id, states,status);
           if(tAllResult > 0) {
               tRiskProcessOperationRecordMapper.updateByIdAndCompletedOneOk(companyId,id,taAllId);
           }
        }
    }

    //安全审核不通过
    public void securityNoPassReview
        (Long companyId,String id,String states,String auditfind,Long userId){
        List<TRiskCheckProcessList> proList=tRiskCheckProcessMapper.
            getByCheckProcessAndTRiskidentevalsId(companyId,id);
        List<TRiskTaskAllocationList> allList=tRiskTaskAllocationMapper.
            selectByNewTaskAll(companyId,id);
        StringBuilder str  = new StringBuilder();
        List<String> recipientIdList = new ArrayList<>();
        for (int i = 0; i < proList.size(); i++) {
            recipientIdList.add(proList.get(i).getDepaReviewer());
        }
        for(int i=0;i<recipientIdList.size();i++){
            if(i==recipientIdList.size()-1)//当循环到最后一个的时候 就不添加逗号,
            {
                str.append(recipientIdList.get(i));
            }
            else {
                str.append(recipientIdList.get(i));
                str.append(",");
            }
        }
        String recipientIds = str.toString();
        int result = tRiskIdentEvalStatusMapper.securityNoPassReview(companyId,id,states,recipientIds);
        if(result == 1) {
            String status = "12";//审核不通过
            int tAllResult = tRiskTaskAllocationMapper.securityNoPassReview
                (companyId, id, states,status);
            if(tAllResult > 0){
                tRiskProcessOperationRecordMapper.updateByIdAndCompletedTwoNoPass(companyId,id);
            }
        }
    }

    //安全审核通过
    public void securityPassReview
        (Long companyId,String id,String states,String auditfind,Long userId){
        //顶级部门
        Organization topPid =organizationMapper.getByTopPid(companyId);
        String recipientIds = String.valueOf(topPid.getLeadUserid());
        List<TRiskTaskAllocationList> allList=tRiskTaskAllocationMapper.
            selectByNewTaskAll(companyId,id);
        int result = tRiskIdentEvalStatusMapper.securityPassReview(companyId,id,states,recipientIds);
        if(result == 1) {
            String status = "11";//审核通过
            int tAllResult = tRiskTaskAllocationMapper.securityPassReview
                (companyId, id, states,status);
            if(tAllResult > 0){
                tRiskProcessOperationRecordMapper.updateByIdAndCompletedTwoOk(companyId,id);
            }
        }
    }

    //最终审核不通过
    public void finalNoPassReview(Long companyId,String id,String states,String auditfind,Long userId){
        List<TRiskCheckProcessList> allList=tRiskCheckProcessMapper.
            getByCheckProcessAndTRiskidentevalsId(companyId,id);
        StringBuilder str  = new StringBuilder(); 
        List<String> recipientIdList = new ArrayList<>();
            for (int i = 0; i < allList.size(); i++) {
                recipientIdList.add(allList.get(i).getDepaReviewer());
            }
            for(int i=0;i<recipientIdList.size();i++){
                if(i==recipientIdList.size()-1)//当循环到最后一个的时候 就不添加逗号,
                {
                    str.append(recipientIdList.get(i));
                }
                else {
                    str.append(recipientIdList.get(i));
                    str.append(",");
                }
            }
        String recipientIds = str.toString();
        int result = tRiskIdentEvalStatusMapper.finalNoPassReview(companyId,id,states,recipientIds);
        if(result == 1) {
            String status = "9";//审核不通过
            int tAllResult = tRiskTaskAllocationMapper.finalNoPassReview
                (companyId, id, states,status);
            if(tAllResult > 0) {
                tRiskProcessOperationRecordMapper.updateByIdAndCompletedThreeNoPass(companyId,id);
            }
        }
    }

    //最终审核通过
    public void finalPassReview(Long companyId,String id,String states,String auditfind,Long userId) {
        
        TRiskIdentEvalStatusList rIdent=tRiskIdentEvalStatusMapper.getByIds(companyId, id);

        List<TRiskProcessOperationRecordList> prOpReList= tRiskProcessOperationRecordMapper.
            getByOperatorAndEnd(companyId,String.valueOf(userId));
        
        List<TRiskTaskAllocationList> allList=tRiskTaskAllocationMapper.
            selectByNewTaskAll(companyId,id);
        List<String> tAllIdList = new ArrayList<>();
        for (int i = 0; i < allList.size(); i++) {
            tAllIdList.add(allList.get(i).getId().toString());
        }
        
        List<TRiskLedgerStatusList> rLedStaList = new ArrayList<>();
        
        List<TRiskTaskAllocationList> taskAllList = tRiskTaskAllocationMapper.
            selectByNewTaskAll(companyId,id);
        List<String> riPoIdList = new ArrayList<>();
        for (int i = 0; i < taskAllList.size() ; i++) {
            riPoIdList.add(String.valueOf(taskAllList.get(i).getRiskpointsId()));
        }
        
        List<TEquipFacStatusList> facStaList = tEquipFacStatusMapper.getByIdList(companyId, riPoIdList); 
        
        List<TRiskCheckItemsList> rCheckList = tRiskCheckItemsMapper.
            getByTridentId(companyId, id,tAllIdList);
        List<String> cheItIdList = new ArrayList<>();
        for (int i = 0; i < rCheckList.size(); i++) {
            cheItIdList.add(rCheckList.get(i).getId().toString());
        }
        
        List<TRiskAssessmentMeasuresList> tRAssMea=tRiskAssessmentMeasuresMapper
            .getByTAllIdCheckitemsId(companyId,tAllIdList,cheItIdList);
        List<String> tRAssMeaList = new ArrayList<>();
        for (int i = 0; i < tRAssMea.size(); i++) {
            tRAssMeaList.add(tRAssMea.get(i).getId().toString());
        }
        
        //检查项中的数值和颜色
        List<TRiskValueLevelList> rValAndLe = tRiskValueLevelMapper.
            getValueLevelAndRiskAsId(companyId,tRAssMeaList);
        
        //作业活动清单中
        List<TRiskJobCheckItemList> tJobCheckList = tRiskJobCheckItemMapper.
            getByTridentId(companyId, id,tAllIdList);
        List<String> tJobItIdList = new ArrayList<>();
        for (int i = 0; i < tJobCheckList.size(); i++) {
            tJobItIdList.add(tJobCheckList.get(i).getId().toString());
        }
        
        //
        List<TRiskProcessInspectionItemList> tProInspList = tRiskProcessInspectionItemMapper.
            getByTridentId(companyId, id,tAllIdList);
        List<String> tProInspIdList = new ArrayList<>();
        for (int i = 0; i < tProInspList.size(); i++) {
            tProInspIdList.add(tProInspList.get(i).getId().toString());
        }
        
        StringBuilder str  = new StringBuilder();
        List<String> recipientIdList = new ArrayList<>();
            for (int i = 0; i < allList.size(); i++) {
                recipientIdList.add(allList.get(i).getAuditor());
            }
            for(int i=0;i<recipientIdList.size();i++){
                if(i==recipientIdList.size()-1)//当循环到最后一个的时候 就不添加逗号,
                {
                    str.append(recipientIdList.get(i));
                }
                else {
                    str.append(recipientIdList.get(i));
                    str.append(",");
                }
            }
        String recipientIds = str.toString();
        int result = tRiskIdentEvalStatusMapper.finalPassReview(companyId,id,states,recipientIds);
        if(result == 1) {
            String status = "0";//审核通过
            int tAllResult = tRiskTaskAllocationMapper.finalPassReview(companyId, id, states,status);
            if(tAllResult > 0){
                tRiskProcessOperationRecordMapper.updateByIdAndCompletedThreeOk(companyId,id);
            }
        }
        List<String> list = new ArrayList<>();
        for (int i = 0; i < taskAllList.size(); i++) {
            list.add(String.valueOf(taskAllList.get(i).getRiskpointsId()));
        }
        tEquipFacStatusMapper.updateByIdStatus(list);
        if(rIdent.getRiskpointType().equals("ss00")){
            for (int i = 0; i < rCheckList.size() ; i++) {
                TRiskLedgerStatusList rLedSta=new TRiskLedgerStatusList();
                rLedSta.setCompanyId(companyId);
                rLedSta.setTriskidentevalsId(Integer.valueOf(id));
                rLedSta.setRiskPointType(rIdent.getRiskpointType());
                rLedSta.setRiskPointsId(taskAllList.get(i).getRiskpointsId());
                rLedSta.setCheckItemId(rCheckList.get(i).getId().intValue());
                rLedSta.setLevelEval(rValAndLe.get(i).getExiApprLevel());
                rLedSta.setLevelRisk(rValAndLe.get(i).getExiRiskLevel());
                rLedSta.setLevelProp(rValAndLe.get(i).getExiRiskConLevel());
                rLedSta.setRiskAssmeaId(Integer.valueOf(tRAssMeaList.get(0)));
                rLedSta.setControlLevel(rValAndLe.get(i).getExiRiskConLevel());
                rLedSta.setLocale(facStaList.get(i).getPositionId().toString());
                rLedSta.setEval(taskAllList.get(i).getEvaluationMethodId());
                rLedSta.setRiskValue(rValAndLe.get(i).getExiRiskValue());
                rLedSta.setRiskColor(rValAndLe.get(i).getExiRiskColor());
                rLedSta.setTime(new Date());
                rLedSta.setUnit(facStaList.get(i).getAdministerId().toString());
                rLedSta.setPersonLiable(facStaList.get(i).getHead());
                rLedSta.setRiskSource("辨识评价计划");
                rLedStaList.add(rLedSta);
            }
            tRiskLedgerStatusMapper.insertLedgerStaList(rLedStaList);
        }else if(rIdent.getRiskpointType().equals("zy00")){
            for (int i = 0; i < tJobCheckList.size() ; i++) {
                TRiskLedgerStatusList rLedSta=new TRiskLedgerStatusList();
                rLedSta.setCompanyId(companyId);
                rLedSta.setTriskidentevalsId(Integer.valueOf(id));
                rLedSta.setRiskPointType(rIdent.getRiskpointType());
                rLedSta.setRiskPointsId(taskAllList.get(i).getRiskpointsId());
                rLedSta.setCheckItemId(tJobCheckList.get(i).getId().intValue());
                rLedSta.setLevelEval(rValAndLe.get(i).getExiApprLevel());
                rLedSta.setLevelRisk(rValAndLe.get(i).getExiRiskLevel());
                rLedSta.setLevelProp(rValAndLe.get(i).getExiRiskConLevel());
                rLedSta.setRiskAssmeaId(Integer.valueOf(tRAssMeaList.get(0)));
                rLedSta.setControlLevel(rValAndLe.get(i).getExiRiskConLevel());
                rLedSta.setLocale(facStaList.get(i).getPositionId().toString());
                rLedSta.setEval(taskAllList.get(i).getEvaluationMethodId());
                rLedSta.setRiskValue(rValAndLe.get(i).getExiRiskValue());
                rLedSta.setRiskColor(rValAndLe.get(i).getExiRiskColor());
                rLedSta.setTime(new Date());
                rLedSta.setUnit(facStaList.get(i).getAdministerId().toString());
                rLedSta.setPersonLiable(facStaList.get(i).getHead());
                rLedSta.setRiskSource("辨识评价计划");
                rLedStaList.add(rLedSta);
            }
            tRiskLedgerStatusMapper.insertLedgerStaList(rLedStaList);
        }else if(rIdent.getRiskpointType().equals("gy00")){
            for (int i = 0; i < tProInspList.size() ; i++) {
                TRiskLedgerStatusList rLedSta=new TRiskLedgerStatusList();
                rLedSta.setCompanyId(companyId);
                rLedSta.setTriskidentevalsId(Integer.valueOf(id));
                rLedSta.setRiskPointType(rIdent.getRiskpointType());
                rLedSta.setRiskPointsId(taskAllList.get(i).getRiskpointsId());
                rLedSta.setCheckItemId(tProInspList.get(i).getId().intValue());
                rLedSta.setLevelEval(rValAndLe.get(i).getExiApprLevel());
                rLedSta.setLevelRisk(rValAndLe.get(i).getExiRiskLevel());
                rLedSta.setLevelProp(rValAndLe.get(i).getExiRiskConLevel());
                rLedSta.setRiskAssmeaId(Integer.valueOf(tRAssMeaList.get(0)));
                rLedSta.setControlLevel(rValAndLe.get(i).getExiRiskConLevel());
                rLedSta.setLocale(facStaList.get(i).getPositionId().toString());
                rLedSta.setEval(taskAllList.get(i).getEvaluationMethodId());
                rLedSta.setRiskValue(rValAndLe.get(i).getExiRiskValue());
                rLedSta.setRiskColor(rValAndLe.get(i).getExiRiskColor());
                rLedSta.setTime(new Date());
                rLedSta.setUnit(facStaList.get(i).getAdministerId().toString());
                rLedSta.setPersonLiable(facStaList.get(i).getHead());
                rLedSta.setRiskSource("辨识评价计划");
                rLedStaList.add(rLedSta);
            }
            tRiskLedgerStatusMapper.insertLedgerStaList(rLedStaList);
        }
        
    }

    //审核中的退回按钮 状态审核中(5)改为辨识中(3)
    public void auditDecomposeRiskIdenEva(
            Long companyId,String triskidentevalsId,String state,Long userId){
        int result = tRiskIdentEvalStatusMapper.auditDecomposeRiskIdenEva
                (companyId,triskidentevalsId,state);
        if(result == 1){
            String status = "3";//风险点评价中 退回后状态辨识中
            tRiskTaskAllocationMapper.auditDecomposeRTaskAllocation(companyId,
                    triskidentevalsId,state,status);
        }
        List<TRiskTaskAllocationList> taskAllList = tRiskTaskAllocationMapper
                .getById(companyId, triskidentevalsId);
        for (TRiskTaskAllocationList  taskAll : taskAllList) {

            Information info = new Information();
            info.setTitle("风险辨识评价计划等待辨识");
            info.setDepartment(String.valueOf(companyId));
            info.setStatus("0");
            info.setDetails("风险辨识评价计划已分解,请尽快辨识!!");
            info.setSendId(Long.valueOf(taskAll.getPersonidenEva()));//发送者
            info.setTargetId(Long.valueOf(taskAll.getDiscerner()));//接收者
            info.setCreateTime(new Date());
            info.setUpdateTime(new Date());
            informationMapper.insertInfo(info);

        }

    }

    public Page<TRiskIdentEvalStatusList> getById
            (BaseReqQuery reqdata, Long companyId,String id) {
        PageHelper.startPage(reqdata.getPageNum(), reqdata.getPageSize());
        Page<TRiskIdentEvalStatusList> evaPagedata =tRiskIdentEvalStatusMapper
                .getById(reqdata.getSearchKey(),companyId,id);
        return evaPagedata;
    }

    public Page<TRiskIdentEvalStatusList> getExportRiskIdentEvalStatusList
            (Long companyId,String id){
        List<Object> list = getObjeList(id);
        return tRiskIdentEvalStatusMapper.getExportRiskIdentEvalStatusList
                (companyId,list);
    }

    public List<Object> getObjeList(String ids) {
        List<Object> list = new ArrayList<Object>();
        String[] str = ids.split(",");
        long[] strArrNum = (long[]) ConvertUtils.convert(str,long.class);
        for (Long id : strArrNum) {
            list.add(id);
        }
        return list;
    }


}
